<?php

class RedisPool
{
    protected $pool;

    function __construct()
    {
        $this->pool = new SplQueue;
    }

    function put($redis)
    {
        $this->pool->push($redis);
    }

    function get()
    {
        //有空闲连接
        if (count($this->pool) > 0)
        {
            // 取出第一个连接
            // $this->pool->shift();
            // 取出最后一个连接
            return $this->pool->pop();
        }

        //无空闲连接，创建新连接
        $redis = new Swoole\Coroutine\Redis();
        $res = $redis->connect('127.0.0.1', 6379);
        if ($res == false)
        {
            return false;
        }
        else
        {
            return $redis;
        }
    }
}


// 有限容量的连接池，用完自动回收
class Pool
{
    protected $pool;
    protected $redis;

    function __construct($config)
    {
        $this->config = $config;

        Co\run(function() use($config){
            $this->pool = new chan($config['pool_size']);

            for($i=0; $i<$config['pool_size']; $i++){
                go(function() use($config){
                    $redis = new Swoole\Coroutine\Redis();
                    $res = $redis->connect($this->config['host'], $this->config['port']);
                    $this->pool->push($redis, $this->config['pool_get_timeout']);
                });
            }
        });
    }

    function get()
    {
        //有空闲连接
        if ($this->pool->length() > 0)
        {
            // 取出第一个连接
            $this->redis = $this->pool->pop($this->config['pool_get_timeout']);
            if(false == $this->redis){
                throw new RuntimeException('redis timeout');
            }

            //使用完后回收连接
            defer(function(){
                $this->pool->push($this->redis);
            });
            return $this->redis;
        }else{
            return false;
        }
    }
}

$config = [
    'pool_size' => 8,
    'pool_get_timeout' => 0.5,
    'host' => '127.0.0.1',
    'port' => 6379,
];

// $pool = new RedisPool();
$pool = new Pool($config);
$server = new Swoole\Http\Server('0.0.0.0', 9501);

$server->on('Request', function($req, $resp) use ($pool) {
    //从连接池中获取一个Redis协程客户端
    $redis = $pool->get();
    //连接失败
    if ($redis === false)
    {
        $resp->end("ERROR");
        return;
    }
    $result = $redis->get('hello');
    $resp->end($result);
    //释放客户端，其他协程可复用此对象
    // $pool->put($redis);
});

$server->start();